import './assets/main.css'

import {createApp} from 'vue'
import {createPinia} from 'pinia'

import App from './App.vue'
import router from './router'
import createCache from "@/stores/cache";

import 'virtual:svg-icons-register'
import plugins from '@/plugins'

import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'

import * as epIconsVue from '@element-plus/icons-vue'
import {getItem} from "@/utils/SystemUtil";
import {userAutoAuthorize} from "@/apis";
import {useStore} from "@/stores";
import {executeLoginByCode, executeLoginSuccess, getUserData} from "@/utils/LoginUtil";
import {CACHE_INCLUDED_ROUTES} from "@/stores/conf";

const app = createApp(App)
for (const [key, component] of Object.entries(epIconsVue)) {
    app.component(key, component)
}

const sessionCache = createCache({mode: 'session'});

app.use(createCache())
app.use(sessionCache)

app.use(ElementPlus)
app.use(createPinia())
app.use(router)
app.use(plugins)

const LOGIN_URL: string = '/user/login';
const defHome: string = '/platform-list';

const isLoginUrl = (url: string) => {
    return url == LOGIN_URL;
}

const initLogin = async (store: any) => {
    store.setTopMenuMap({
        'PlatformList': {
            routeName: 'platform',
            routePath: '/platform',
            component: '/Platform'
        },
        'RealmList': {
            routeName: 'realm',
            routePath: '/realm',
            component: '/Realms'
        }
    })
}

const mountApp = async (path: string) => {
    await router.replace({
        path: path,
        query: {}
    });
    app.mount('#app');
}

const getUrlParams = (store: any) => {
    const params: URLSearchParams = new URLSearchParams(window.location.search);

    const urlParams: any = {
        authMode: params.get('mode'),
        platform: params.get('platform') || '',
        clientId: params.get('client_id') || '',
        clientSecret: params.get('client_secret') || '',
    }

    store.setLoginParam(urlParams);

    return urlParams;
}

const executeThirdLogin = async (store: any, urlParams: any) => {
    const sessionId: string = getItem('UNI_MASTER_SESSION_ID') || '';
    const ssoMode: string = urlParams.authMode;

    if (sessionId && ssoMode === 'sso') {
        const result = await userAutoAuthorize(urlParams.clientId, urlParams.clientSecret, urlParams.platform);
        if (result && result.code === 0 && result.data) {
            window.location.href = result.data.redirectUri;
        } else {
            await mountApp(LOGIN_URL);
        }
    } else {
        await mountApp(LOGIN_URL);
    }
}

const handleCenterLogin = async (store: any, pathName: string) => {
    const sessionId: string = getItem('UNI_MASTER_SESSION_ID') || '';
    const userData: any = await getUserData();

    if (userData) {
        await executeLoginSuccess(userData, pathName);
        await mountApp(pathName);
    } else if (sessionId) {
        // 如果会话存在了，自动登录
        const result = await userAutoAuthorize('', '', '');
        if (result && result.code === 0 && result.data) {
            const redirectUri: string = result.data.redirectUri;
            const pos: number = redirectUri.indexOf('code=');
            if (await executeLoginByCode(redirectUri.substring(pos + 5), defHome)) {
                await mountApp(pathName || store.getHomeRoute());
                return;
            }
        }
        await mountApp(LOGIN_URL);
    } else {
        // 从后台获取Token，完成登录
        await mountApp(LOGIN_URL);
    }
}

const ssoCheck = async () => {
    const store = useStore();
    const urlParams: any = getUrlParams(store);

    // 执行第三方平台单点登录
    if (urlParams.platform) {
        await executeThirdLogin(store, urlParams);
    } else {
        await initLogin(store);
        await handleCenterLogin(store, defHome);
    }
}

ssoCheck().then(r => console.log(r));
